<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use App\Http\Model\Faq;
use App\Helpers\SuccessResponse;
use App\Helpers\ValidatorResponse;
use Illuminate\Support\Facades\DB;
use App\Http\Constant;

class FaqController extends Controller{

	public function __construct(){

	}

	public function detail($id){
		$validate = Validator::make(['id' => $id], [
			'id' => 'required|integer|min:1',
		]);
		if($validate->fails()){
			return ValidatorResponse::handler($validate->errors());
		}else{
			$faq_model = new Faq(); 
			$faq_data = $faq_model->where('id', $id)->get()->toArray();
			if(0 == count($faq_data)){
				return SuccessResponse::handler('['.Constant::EC_NO_FAQ_MATCHED.'] No validate faq found.');
			}else{
				return SuccessResponse::handler($faq_data);
			}
		}
	}


	// is_page      whether to pagenating
	// show_page 	 show current_page, total_count, total_page
	// current_page
	// page_count   how many rows per page
	// order_by     order by which fields, default id desc
	// news_status  -1:all, 0:draft
	public function listFaq(Request $request){
		$is_page = intval($request->input('is_page')) == 1 ? 1 : 0;
		$show_page = intval($request->input('show_page')) == 1 ? 1 : 0;
		$current_page = intval($request->input('current_page'));
		$current_page = $current_page > 1 ? $current_page : 1;
		$page_count = intval($request['page_count']);
		$page_count = $page_count > 0 ? $page_count : 20;
		$category_ids = json_decode($request->input('category_ids'), true);
		if(0 == count($category_ids)){
			$category_ids = false;
		}else{
			$category_ids = array_values($category_ids);
		}
		$faq_status = json_decode($request->input('faq_status'), true);
		if(0 == count($faq_status)){
			$faq_status = array(
				Constant::TFEX_FAQ_CATEGORY_STATUS_OPEN,
				Constant::TFEX_FAQ_CATEGORY_STATUS_CLOSE,
			);
		}else{
			$faq_status = array_values($faq_status);
		}
		$keywords = trim(strval($request->input('keywords')));
		$order_by = json_decode($request->input('order_by'), true);
		if(0 != count($order_by)){
			$order_by_arr = array();
			foreach ($order_by as $key => $value) {
				if($value == 'desc' || $value == 'asc'){
					array_push($order_by_arr, $key.' '.$value);
				}else{
					continue;
				}
			}
			$order_by = implode(',', $order_by_arr);
		}else{
			$order_by = 'id desc';
		}

		$faq_model = new Faq();
		if($is_page){
			$data_sql = 'select * from faq';
			if($category_ids || $faq_status || strlen($keywords)){
				$data_sql .= ' where 1=1';
			}
			if($category_ids){
				$data_sql .= ' and category_id in ('.implode(',', $category_ids).')';
			}
			if($faq_status){
				$data_sql .= ' and status in ('.implode(',', $faq_status).')';
			}
			if(strlen($keywords)){
				$data_sql .= ' and ( title like "%'.$keywords.'%")';
			}
			$data_sql .= ' order by '.$order_by;
			$limit_start = ($current_page - 1) * $page_count;
			$data_sql .= ' limit '.$limit_start.','.$page_count;
			$faq_data = DB::select($data_sql);
			$page_info = array(
				'total' => count($faq_data),
				'total_page' => 1,
			);
			if($show_page){
				$count_sql = 'select count(*) as total from faq';
				if($category_ids || $faq_status || strlen($keywords)){
					$count_sql .= ' where 1=1';
					if($category_ids){
						$count_sql .= ' and category_id in ('.implode(',', $category_ids).')';
					}
					if($faq_status){
						$count_sql .= ' and status in ('.implode(',', $faq_status).')';
					}
					if(strlen($keywords)){
						$count_sql .= ' and ( title like "%'.$keywords.'%" )';
					}
				}
				$faq_count = DB::select($count_sql);
				$faq_count = json_decode(json_encode($faq_count), true);
				$page_info = array(
					'total' => $faq_count[0]['total'],
					'total_page' => ceil($faq_count[0]['total'] / $page_count),
				);
			}
		}else{
			$data_sql = 'select * from faq';
			if($category_ids || $faq_status || strlen($keywords)){
				$data_sql .= ' where 1=1';
				if($category_ids){
					$data_sql .= ' and category_id in ('.implode(',', $category_ids).')';
				}
				if($faq_status){
					$data_sql .= ' and status in ('.implode(',', $faq_status).')';
				}
				if(strlen($keywords)){
					$data_sql .= ' and ( title like "%'.$keywords.'%" )';
				}
			}
			$data_sql .= ' order by '.$order_by;
			$data_sql .= ' limit 0,999';
			$faq_data = DB::select($data_sql);
			$page_info = array(
				'total' => count($faq_data),
				'total_page' => 1,
			);
		}

		$rtn_data = array(
			'where' => array(
				'is_page' => $is_page,
				'show_page' => $show_page,
				'current_page' => $current_page,
				'page_count' => $page_count,
				'order_by' => $order_by,
				'faq_status' => $faq_status,
				'keywords' => $keywords,
				'category_ids' => $category_ids,
			),
			'data' => $faq_data,
		);
		if($show_page){
			$rtn_data['show_page'] = $page_info;
		}
		return SuccessResponse::handler($rtn_data);
	}

	public function add(Request $request){
		$validate = Validator::make($request->all(), [
			'title' => 'required|string',
			'content' => 'required|string',
            'category_id' => 'required|integer|min:1',
            'status' => 'required|integer|min:1',
        ]);
		if($validate->fails()){
			return ValidatorResponse::handler($validate->errors());
		}else{
			$faq_model = new Faq();
			$faq_model->title = $request->input('title');
			$faq_model->content = $request->input('content');
			$faq_model->category_id = $request->input('category_id');
			$faq_model->status = $request->input('status');
			try{
				$faq_model->save();
			}catch(\Exception $e){
				return SuccessResponse::handler('['.$e->getCode().'] '.$e->getMessage());
			}
			$faq_data['id'] = $faq_model->id;
			return SuccessResponse::handler($faq_data);
		}
	}

	public function edit(Request $request){
		$validate = Validator::make($request->all(), [
			'id' => 'required|integer|min:1',
			'title' => 'required|string',
			'content' => 'required|string',
            'category_id' => 'required|integer|min:1',
            'status' => 'required|integer|min:1',
        ]);
        if($validate->fails()){
			return ValidatorResponse::handler($validate->errors());
		}else{
			$faq_model = new Faq();
			$faq_data = array(
				'title' => $request->input('title'),
				'content' => $request->input('content'),
				'category_id' => $request->input('category_id'),
				'status' => $request->input('status'),
			);
			try{
				$faq_model->where('id', $request->input('id'))->update($faq_data);
			}catch(\Exception $e){
				return SuccessResponse::handler('['.$e->getCode().'] '.$e->getMessage());
			}
			$faq_data['id'] = $request->input('id');
			return SuccessResponse::handler($faq_data);
		}
	}

	public function delete(Request $request){
		$faq_ids = json_decode($request->input('id'), true);
		if(0 == count($faq_ids)){
			return SuccessResponse::handler('['.Constant::EC_NO_VALIDATE_FAQ_IDS.'] No validate faq id or ids privided.');
		}else{
			$faq_model = new Faq();
			$update_data = array(
				'status' => Constant::TFEX_FAQ_STATUS_DELETE,
			);
			try{
				$faq_model->whereIn('id',  array_values($faq_ids))->update($update_data);
			}catch(\Exception $e){
				return SuccessResponse::handler('['.Constant::EC_SYSTEM_ERROR.'] An error accurred in system.');
			}
			return SuccessResponse::handler(array('id' => $faq_ids));
		}
	}

	public function open(Request $request){
		$faq_ids = json_decode($request->input('id'), true);
		if(0 == count($faq_ids)){
			return SuccessResponse::handler('['.Constant::EC_NO_VALIDATE_FAQ_IDS.'] No validate faq id or ids privided.');
		}else{
			$faq_model = new Faq();
			$update_data = array(
				'status' => Constant::TFEX_FAQ_STATUS_OPEN,
			);
			try{
				$faq_model->whereIn('id',  array_values($faq_ids))->update($update_data);
			}catch(\Exception $e){
				return SuccessResponse::handler('['.Constant::EC_SYSTEM_ERROR.'] An error accurred in system.');
			}
			return SuccessResponse::handler(array('id' => $faq_ids));
		}
	}

	public function close(Request $request){
		$faq_ids = json_decode($request->input('id'), true);
		if(0 == count($faq_ids)){
			return SuccessResponse::handler('['.Constant::EC_NO_VALIDATE_FAQ_IDS.'] No validate news id or ids privided.');
		}else{
			$faq_model = new Faq();
			$update_data = array(
				'status' => Constant::TFEX_FAQ_STATUS_CLOSE,
			);
			try{
				$faq_model->whereIn('id',  array_values($faq_ids))->update($update_data);
			}catch(\Exception $e){
				return SuccessResponse::handler('['.Constant::EC_SYSTEM_ERROR.'] An error accurred in system.');
			}
			return SuccessResponse::handler(array('id' => $faq_ids));
		}
	}
}
